<script setup lang="ts">
import { onMounted, ref, reactive, onUnmounted, onActivated, watch } from 'vue';
import { Global } from "../../Global";
import { HttpHelper } from "../../lib/HttpHelper";
import { ElTable, ElForm } from 'element-plus';
import DocEditor from '../../components/DocEditor.vue';
import UploadPicture from '../../components/UploadPicture.vue';
import ActivityJoinView from "./ActivityJoinView.vue";

const isLoading = ref(false);
const isBusy = ref(false);
const listDatas = ref(<any[]>[]);
const pageNumber = ref(1);
const servicePath = '/ActivityActivity';
const total = ref(0);
const formData = ref(<any>{});
var editingData: any;
const dialogFormVisible = ref(false);
const dialogDetailVisible = ref(false);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<any[]>([]);
const formRef = ref<InstanceType<typeof ElForm>>();

    const activityId = ref();
const searchData = reactive({

    PageIndex: 0,
    PageSize: 10
});

const rules = reactive({
    Title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
    Introduction: [{ required: true, message: '请输入介绍', trigger: 'blur' }],
    JoinStartTime: [{ required: true, message: '请输入报名开始时间', trigger: 'blur' }],
    JoinEndTime: [{ required: true, message: '请输入报名截止时间', trigger: 'blur' }],
    BeginTime: [{ required: true, message: '请输入活动开始时间', trigger: 'blur' }],
    EndTime: [{ required: true, message: '请输入活动结束时间', trigger: 'blur' }],
});

const resetFormData = () => {
    formData.value = {
        Title: null,
        Sponsor: null,
        Location: null,
        Introduction: null,
        ImgUrl: null,
        JoinStartTime: null,
        JoinEndTime: null,
        BeginTime: null,
        EndTime: null,
        Sort: 100,
    };
}

onActivated(() => {
    bindList();
});

onUnmounted(() => {
    console.log("卸载了");
});

const refreshClick = () => {
    bindList();
}

const bindList = async () => {
    isLoading.value = true;
    try {
        searchData.PageIndex = pageNumber.value - 1;
        var json = await HttpHelper.postJson(`${servicePath}/List`, searchData);
       
        var list = JSON.parse(json);
        console.log(JSON.stringify(list.Datas));
        total.value = list.Total;
        listDatas.value.splice(0, listDatas.value.length);
        listDatas.value.push(...list.Datas);

        if (listDatas.value.length == 0 && pageNumber.value > 1) {
            pageNumber.value--;
            bindList();
        }
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isLoading.value = false;
    }
}

const addClick = () => {
    resetFormData();
    dialogFormVisible.value = true;
}

const editClick = (row: any) => {
    resetFormData();
    for (var p in row) {
        formData.value[p] = row[p];
    }
    editingData = row;
    dialogFormVisible.value = true;
}

const deleteClick = async () => {
    if (isLoading.value)
        return;

    if (multipleSelection.value.length == 0) {
        Global.showInfo("请选择需要删除的数据");
        return;
    }

    if (confirm("确定删除吗？")) {
        try {
            isLoading.value = true;
            var requestData = new FormData();
            multipleSelection.value.forEach(x => {
                requestData.append("ids", x.id);

            });
            await HttpHelper.postFormData(`${servicePath}/Delete`, requestData);
            multipleSelection.value.forEach(x => {
                var index = listDatas.value.findIndex(m => m == x);
                if (index >= 0) {
                    listDatas.value.splice(index, 1);
                }

            });
            multipleTableRef.value?.clearSelection();
        } catch (error) {
            Global.showError(error);
        }
        finally {
            isLoading.value = false;
        }
    }
}

const handleSelectionChange = (selecteds: any[]) => {
    multipleSelection.value = selecteds;
}

const submitClick = async () => {
    try {
        await formRef.value?.validate();
    } catch (error) {
        return;
    }

    try {
        isBusy.value = true;
        console.log(JSON.stringify(formData.value));

        if (formData.value.id) {
          
            var obj = JSON.parse(await HttpHelper.postJson(`${servicePath}/Modify`, formData.value));
            listDatas.value.splice(listDatas.value.indexOf(editingData), 1, obj);
        }
        else {
            formData.value = JSON.parse(await HttpHelper.postJson(`${servicePath}/Add`, formData.value));
            listDatas.value.splice(0, 0, formData.value);
        }
        dialogFormVisible.value = false;
    } catch (error) {
        Global.showError(error);
    }
    finally {
        isBusy.value = false;

    }
}

const goSearch = () => {
    pageNumber.value = 1;
    bindList();
}
</script>
<template>
    <div class="page-view-main">
        <div
            style="padding: var(--page-padding); flex: 1 1 0%; min-height: 0px; display: flex; flex-direction: column;">
            <div class="page-view-panel">
                <div style="display: flex; flex-direction: row; margin-bottom: 10px;">
                    <div style="flex: 1 1 0%;">

                    </div>
                    <div><el-button-group class="ml-4">
                            <el-button type="default" icon="Plus" @click="addClick">添加</el-button>
                            <el-button type="default" icon="Refresh" @click="refreshClick">刷新</el-button>
                            <el-button type="default" icon="Delete" @click="deleteClick">删除</el-button>
                        </el-button-group></div>
                </div>

                <el-table ref="multipleTableRef" @selection-change="handleSelectionChange" :data="listDatas"
                    cell-class-name="tb-cell" header-cell-class-name="tb-header-cell" table-layout="auto"
                    v-loading="isLoading" style="flex:1;min-height:0px;">
                    <el-table-column type="selection" width="42" fixed="left" />
                    <el-table-column label="封面图">
                        <template #default="scope">
                            <img :src="scope.row.ImgUrl" style="height:100px;"/>
                        </template>
                    </el-table-column>
                    <el-table-column prop="Title" label="活动标题" />
                    <el-table-column prop="Sort" label="推荐排序" />
                    <el-table-column prop="Sponsor" label="主办方" />
                    <el-table-column prop="Location" label="地址" />
                   
                    <el-table-column prop="JoinStartTime" label="报名开始时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="JoinEndTime" label="报名截止时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="BeginTime" label="活动开始时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="EndTime" label="活动结束时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="CreateTime" label="创建时间" :formatter="Global.formatUTCToLocal" />
                    <el-table-column prop="JoinCount" label="参与人数" />

                    <el-table-column label="操作" fixed="right">
                        <template #default="scope">
                            <el-button size="small" type="primary" @click="editClick(scope.row)">
                                编辑
                            </el-button>
                            <el-button size="small" type="warning" @click="activityId=scope.row.id;dialogDetailVisible=true">
                                参与人列表
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <div>
                    <el-pagination @current-change="bindList" small background layout="prev, pager, next" :total="total"
                        v-model:current-page="pageNumber" class="mt-4" style="margin-top: 10px;" />
                </div>
            </div>
        </div>

        <el-dialog v-model="dialogFormVisible" :title="formData.id ? '编辑' : '新增'" :close-on-click-modal="false"
            style="width:70%">
            <el-form ref="formRef" :model="formData" label-width="auto" :rules="rules"
                @keypress.native.enter.prevent="submitClick">

                <el-form-item label="活动标题" prop="Title">
                    <el-input v-model="formData.Title" />
                </el-form-item>
                <el-form-item label="主办方" prop="Sponsor">
                    <el-input v-model="formData.Sponsor" />
                </el-form-item>
                <el-form-item label="地址" prop="Location">
                    <el-input v-model="formData.Location" />
                </el-form-item>
                <el-form-item label="介绍" prop="Introduction">
                    <DocEditor v-model="formData.Introduction"></DocEditor>
                </el-form-item>
                <el-form-item label="封面图" prop="ImgUrl">
                    <UploadPicture v-model="formData.ImgUrl" />
                </el-form-item>
                <el-form-item label="报名开始时间" prop="JoinStartTime">
                    <el-date-picker v-model="formData.JoinStartTime" type="datetime"
                        placeholder="Select date and time" />
                </el-form-item>
                <el-form-item label="报名截止时间" prop="JoinEndTime">
                    <el-date-picker v-model="formData.JoinEndTime" type="datetime"
                        placeholder="Select date and time" />
                </el-form-item>
                <el-form-item label="活动开始时间" prop="BeginTime">
                    <el-date-picker v-model="formData.BeginTime" type="datetime"
                        placeholder="Select date and time" />
                </el-form-item>
                <el-form-item label="活动结束时间" prop="EndTime">
                    <el-date-picker v-model="formData.EndTime" type="datetime"
                        placeholder="Select date and time" />
                </el-form-item>
                <el-form-item label="推荐排序" prop="Sort">
                    <el-input-number v-model="formData.Sort" :precision="0" />
                </el-form-item>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" :loading="isBusy" @click="submitClick">
                        确 定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <el-dialog v-model="dialogDetailVisible" title="参与人列表" :close-on-click-modal="false"
            style="width: 60%;height: 80%;margin: 5vh auto;">
            <ActivityJoinView :ActivityId="activityId"
                style="position: absolute;bottom: 10px;width: 100%;left:0;top:50px;" />
        </el-dialog>
    </div>
</template>
<style scoped lang="scss"></style>
